package cn.jh.common.utils;

import com.google.common.collect.Maps;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.swetake.util.Qrcode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Map;


/**
 * 二维码生成工具类
 *
 * @author Cloud
 * @data 2016-12-15
 * QRCode
 */
public class QRCodeUtil {

    private static Logger log = LoggerFactory.getLogger(Qrcode.class);

    //二维码颜色
    private static final int BLACK = 0xFF000000;
    //二维码颜色
    private static final int WHITE = 0xFFFFFFFF;

    public static void qrCode(String inUrl, String outPath) {
        qrCode(inUrl, outPath, 200, 200, "jpg");
    }

    public static void qrCode(String inUrl, String outPath, Integer width, Integer height, String imageType) {
        Map<EncodeHintType, String> paramMap = Maps.newHashMap();
        //设置编码字符集
        paramMap.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            BitMatrix encode = new MultiFormatWriter().encode(inUrl, BarcodeFormat.QR_CODE, width, height, paramMap);
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int i = 0; i < encode.getWidth(); i++) {
                for (int j = 0; j < encode.getHeight(); j++) {
                    //4、循环将二维码内容定入图片
                    image.setRGB(i, j, encode.get(i, j) ? BLACK : WHITE);
                }
            }
            File codeImage = new File(outPath);
            //如果图片不存在创建图片
            if (!codeImage.exists()) {
                boolean isSuccess = codeImage.createNewFile();
            }
            //5、将二维码写入图片
            ImageIO.write(image, imageType, codeImage);
        } catch (WriterException e){
            log.error("二维码生成失败");
            e.printStackTrace();
        } catch (IOException e) {
            log.error("生成二维码图片失败");
            e.printStackTrace();
        }
    }
}


